<?php
include '../config.php';
include '../scripts/utils.php';

session_start();

$_SESSION = array();

// Connecting, selecting database
$mysqli = new mysqli($MYSQL_HOST, $MYSQL_USERNAME, $MYSQL_PASSWORD, $MYSQL_DB_NAME);
if ($mysqli->connect_errno) {
	logout();
	echo "ERR";
} else {

	$query = sprintf($VERIFY_LOGIN, $_POST["username"]);

	$verify = $mysqli->query($query);
	
	if (!$verify) {
		mysqli_free_result($verify);
		$mysqli->close();
		logout();
		echo "ERR";
	} else {
		if ($verify->num_rows) {
			$user = $verify->fetch_assoc();
			$password = $_POST["password"];
			$hash = crypt($password, $PSW_SALT);
			for ($i = 0; $i < $HASHING_ITERATIONS; ++$i)
			{
				$hash = crypt($hash . $password, $PSW_SALT);
			}
			if ($user["password"] == $hash) {
				mysqli_free_result($verify);
				$mysqli->close();
				$_SESSION["id_utente"] = $user["userId"];
				$_SESSION["email"] = $user["email"];
				$_SESSION["id_issuer"] = $user["idIssuer"];
				$_SESSION["admin"] = ($user["admin"] == TRUE);
				echo "OK";
			} else {
				mysqli_free_result($verify);
				$mysqli->close();
				logout();
				echo "KO";
			}
		} else {
			mysqli_free_result($verify);
			$mysqli->close();
			logout();
			echo "NO";
		}
	}
}
?>
